package com.yanqu.road.server.manager.systemgroup.newmonopolymkt;

import com.yanqu.road.dao.impl.nenmonopolymarket.CrossNewMonopolyMarketUserDataDaoImpl;
import com.yanqu.road.dao.impl.nenmonopolymarket.NewMonopolyMarketNoticeDataDaoImpl;
import com.yanqu.road.dao.impl.nenmonopolymarket.NewMonopolyMarketServerAbilityDataDaoImpl;
import com.yanqu.road.dao.impl.nenmonopolymarket.NewMonopolyMarketWeekStateDataDaoImpl;
import com.yanqu.road.entity.enums.eMonopolyMarketResType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.monopolymarket.office.MonopolyMarketOfficeSeatConfig;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.servercenter.ChannelSystemConfig;
import com.yanqu.road.entity.systemgroup.ResourceServerGroup;
import com.yanqu.road.entity.systemgroup.common.SystemServerGroupWeekData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.*;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.config.NewMonopolyMarketResConfigData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.config.NewMonopolyMarketSystemConfigInfo;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.office.NewMonopolyMarketOfficeFinishData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.office.NewMonopolyMarketOfficeSeatData;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.office.NewMonopolyMarketOfficeSeatInfo;
import com.yanqu.road.entity.log.cross.newMonopolyMarket.log.LogNewMonopolyMarketRank;
import com.yanqu.road.entity.log.cross.newMonopolyMarket.log.LogNewMonopolyMarketResUseStat;
import com.yanqu.road.entity.systemgroup.newmonopolymarket.resgrab.*;
import com.yanqu.road.entity.systemgroup.rank.ServerRank;
import com.yanqu.road.entity.systemgroup.rank.ServerRankModel;
import com.yanqu.road.entity.systemgroup.rank.UserRank;
import com.yanqu.road.entity.systemgroup.rank.UserRankModel;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.newmonopolymkt.NewMonopolyMarketProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.config.BattleChannelSystemConfigMgr;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.systemgroup.CrossSystemWeekGroupMatchHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.NewMonopolyMarketCommonMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 新榷场
 * 管理分组
 * 管理榷署
 * 管理王帐
 * 管理王宫
 */
public class CrossNewMonopolyMarketGroup {

    /**
     * 本周系统分组id
     */
    int groupId;

    /**
     * 内部分组信息(大、中、小跨服)
     */
    private NewMonopolyMarketWeekStateData weekStateData;

    /**
     * 榷署逻辑
     */
    private CrossNewMonopolyMarketOffice marketOffice;

    /**
     * 资源争夺逻辑
     */
    private CrossNewMonopolyMarketResRob marketResRob;

    /**
     * 公告 key 分组, 0是榷署
     *
     */
    private Map<Integer, List<NewMonopolyMarketNoticeData>> noticeMap = new ConcurrentHashMap();

    /**
     * 需要入库的 公告
     */
    private List<NewMonopolyMarketNoticeData> needAddNoticeList = new ArrayList<>();

    /**
     * 玩家数据
     * serverId, userId
     */
    private Map<Long, Map<Long, CrossNewMonopolyMarketUserData>> serverUserDataMap = new ConcurrentHashMap<>();

    /**
     * 需要入库的 玩家数据
     */
    private List<CrossNewMonopolyMarketUserData> needAddServerUserDataList = new ArrayList<>();

    /**
     * 个人榜
     */
    private UserRankModel userRankModel ;

    /**
     * 区服榜
     */
    private ServerRankModel serverRankModel;

    /**
     * 区服活跃度
     */
    private Map<Long, NewMonopolyMarketServerAbilityData> serverAbilityDataMap = new ConcurrentHashMap<>();

    /**
     * 聊天
     */
    private WorldMessageProto.WorldMessageListMsg.Builder chatListMsg = WorldMessageProto.WorldMessageListMsg.newBuilder();

    //初始榷场
    public CrossNewMonopolyMarketGroup(SystemServerGroupWeekData groupWeekData) {

        // 加载后台配置
        int channelId = ConfigHelper.getInt("channelId");
        Map<String, ChannelSystemConfig> systemConfigMap = BattleChannelSystemConfigMgr.getSystemConfigMap(channelId, eSystemId.NewMonopolyMarket.getValue());
        if (systemConfigMap == null) {
            throw new RuntimeException("新榷场配置未加载");
        }

        if(!systemConfigMap.containsKey(NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_RULE)){
            CrossNewMonopolyMarketMgr.getLogger().info("系统 {} 缺失 t_s_system_config 配置 {}" , eSystemId.NewMonopolyMarket.getValue(), NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_RULE);
            throw new RuntimeException("新榷场 缺失 t_s_system_config 配置");
        }

        if(!systemConfigMap.containsKey(NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_PERCENT)){
            CrossNewMonopolyMarketMgr.getLogger().info("系统 {} 缺失 t_s_system_config 配置 {}" , eSystemId.NewMonopolyMarket.getValue(), NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_PERCENT);
            throw new RuntimeException("新榷场 缺失 t_s_system_config 配置");
        }

        //中跨服最终区服數量
        Map<Integer, Integer> middleGroupNum = new HashMap<>();
        //小跨服最终区服數量
        Map<Integer, Integer> smallGroupMin = new HashMap<>();

        List<String> rangStringList = StringUtils.stringToStringList(systemConfigMap.get(NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_RULE).getValue(), "\\|");
        for (String str : rangStringList) {
            List<Integer> paramList = StringUtils.stringToIntegerList(str, "-");
            middleGroupNum.put(paramList.get(0), paramList.get(1));
            smallGroupMin.put(paramList.get(0), paramList.get(2));
        }
        if(!middleGroupNum.containsKey(groupWeekData.getOpenDay()) || !smallGroupMin.containsKey(groupWeekData.getOpenDay())){
            throw new RuntimeException("新榷场 中、小跨服分组配置缺失对应的开服天数配置:" + groupWeekData.getOpenDay());
        }

        List<Integer> twoList = StringUtils.stringToIntegerList(systemConfigMap.get(NewMonopolyMarketSystemConfigInfo.QUECHANG_SEVERGROUP_PERCENT).getValue(), "\\|");
        int middleBaiFenBi =  twoList.get(0);
        int smallBaiFenBi =  twoList.get(1);

        NewMonopolyMarketWeekStateData tempStateData = initGroupWeekData(groupWeekData, middleGroupNum, smallGroupMin, middleBaiFenBi, smallBaiFenBi);

        if(tempStateData == null){
            throw new RuntimeException("weekStateData is null");
        }


        this.weekStateData = tempStateData;
        this.groupId = tempStateData.getSystemGroupId();

        this.marketOffice = new CrossNewMonopolyMarketOffice(this);

        this.marketResRob = new CrossNewMonopolyMarketResRob(this);

        this.initNpcBlood();

    }

    /**
     * 中、小跨服划分
     */
    public NewMonopolyMarketWeekStateData initGroupWeekData(SystemServerGroupWeekData groupWeekData, Map<Integer, Integer> middleGroupNum, Map<Integer, Integer> smallGroupMin,
                                                            int middleBaiFenBi, int smallBaiFenBi) {
        int now = DateHelper.getCurrentSecond();
        NewMonopolyMarketWeekStateData stateData = new NewMonopolyMarketWeekStateData();
        stateData.setWeekId(groupWeekData.getWeekId());
        stateData.setSystemGroupId(groupWeekData.getGroupId());
        stateData.setInsertOption();
        stateData.setOpenDays(groupWeekData.getOpenDay());
        stateData.setServerIdList(new ArrayList<>(groupWeekData.getServerIdList()));
        stateData.setOfficeRefreshTime(now);
        stateData.setKingResGrabRefreshTime(now);
        stateData.setQueenResGrabRefreshTime(now);

        int groupId = 0;
        //划分大跨服
        //王帐
        ResourceServerGroup serverGroup = new ResourceServerGroup();
        serverGroup.setGroupId(++groupId);
        serverGroup.setGroupType(3);
//        serverGroup.setServerList();  //大跨服是分组范围
        serverGroup.setResType(eMonopolyMarketResType.RES_KING_NEW.getValue());
        stateData.getInnerGroupList().put(groupId, serverGroup);

        //王宫
        serverGroup = new ResourceServerGroup();
        serverGroup.setGroupId(++groupId);
        serverGroup.setGroupType(3);
//        serverGroup.setServerList();  //大跨服是分组范围
        serverGroup.setResType(eMonopolyMarketResType.RES_QUEEN_NEW.getValue());
        stateData.getInnerGroupList().put(groupId, serverGroup);

        Random random = new Random();
        //划分中跨服
        int middlePerNum = middleGroupNum.get(groupWeekData.getOpenDay());
        int middleMinNum = BigDecimal.valueOf(middlePerNum * middleBaiFenBi).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).intValue();
        List<ResourceServerGroup> middleGroupList = new ArrayList<>();

        List<Long> bigGroupServerIdList = new ArrayList<>(stateData.getServerIdList());

        List<Integer> groupNumList = CrossSystemWeekGroupMatchHelper.divideGroupNum(middlePerNum, middleMinNum, stateData.getServerIdList().size());
        for (int num : groupNumList) {

            if(num > bigGroupServerIdList.size()){
                CrossNewMonopolyMarketMgr.getLogger().info("划分中跨发失败, {}, {}, {}, {},{}", groupId + 1, num, bigGroupServerIdList.size(), groupNumList, stateData.getServerIdList());
                return null;
            }
            ResourceServerGroup middleServerGroup = new ResourceServerGroup();
            middleServerGroup.setGroupType(2);
            middleServerGroup.setGroupId(++groupId);
            //王帐
            middleServerGroup.setResType(eMonopolyMarketResType.RES_KING_NEW.getValue());

            //改为随机
            List<Long> sidList = new ArrayList<>();
            while (sidList.size() < num && bigGroupServerIdList.size() > 0){
                int idx = random.nextInt(bigGroupServerIdList.size());
                sidList.add(bigGroupServerIdList.remove(idx));
            }

            middleServerGroup.setServerList(new ArrayList<>(sidList));

            middleGroupList.add(middleServerGroup);
            stateData.getInnerGroupList().put(groupId, middleServerGroup);

            CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} 中跨服 type {}, resGroupId {},{}", groupWeekData.getWeekId(), groupWeekData.getGroupId(), eMonopolyMarketResType.RES_KING_NEW.getValue(), groupId, sidList);

            //王宫
            middleServerGroup = new ResourceServerGroup();
            middleServerGroup.setGroupType(2);
            middleServerGroup.setGroupId(++groupId);
            middleServerGroup.setResType(eMonopolyMarketResType.RES_QUEEN_NEW.getValue());
            middleServerGroup.setServerList(new ArrayList<>(sidList));
            stateData.getInnerGroupList().put(groupId, middleServerGroup);

            CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} 中跨服 type {}, resGroupId {},{}", groupWeekData.getWeekId(), groupWeekData.getGroupId(), eMonopolyMarketResType.RES_QUEEN_NEW.getValue(), groupId, sidList);
        }
        //划分小跨服
        int smallerPerNum = smallGroupMin.get(groupWeekData.getOpenDay());
        int smallMinNum = BigDecimal.valueOf(smallerPerNum * smallBaiFenBi).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).intValue();
        for (ResourceServerGroup middleServerGroup : middleGroupList) {

            List<Long> middleGroupServerIdList = new ArrayList<>(middleServerGroup.getServerList());

            List<Integer> numList = CrossSystemWeekGroupMatchHelper.divideGroupNum(smallerPerNum, smallMinNum, middleServerGroup.getServerList().size());

            for (int num : numList) {

                if(num > middleGroupServerIdList.size()){
                    CrossNewMonopolyMarketMgr.getLogger().info("划分小跨发失败, {}, {}, {}, {},{}", groupId + 1, num, middleGroupServerIdList.size(), numList, middleServerGroup.getServerList());
                    return null;
                }
                ResourceServerGroup sg = new ResourceServerGroup();
                sg.setGroupType(1);
                sg.setGroupId(++groupId);
                sg.setResType(eMonopolyMarketResType.RES_KING_NEW.getValue());

                List<Long> sidList = new ArrayList<>();
                while (sidList.size() < num && middleGroupServerIdList.size() > 0){
                    int idx = random.nextInt(middleGroupServerIdList.size());
                    sidList.add(middleGroupServerIdList.remove(idx));
                }

                sg.setServerList(new ArrayList<>(sidList));
                stateData.getInnerGroupList().put(groupId, sg);

                CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} 小跨服 type {}, resGroupId {},{}", groupWeekData.getWeekId(), groupWeekData.getGroupId(), eMonopolyMarketResType.RES_KING_NEW.getValue(), groupId, sidList);

                sg = new ResourceServerGroup();
                sg.setGroupType(1);
                sg.setGroupId(++groupId);
                sg.setResType(eMonopolyMarketResType.RES_QUEEN_NEW.getValue());
                sg.setServerList(new ArrayList<>(sidList));
                stateData.getInnerGroupList().put(groupId, sg);

                CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} 小跨服 type {}, resGroupId {},{}", groupWeekData.getWeekId(), groupWeekData.getGroupId(), eMonopolyMarketResType.RES_QUEEN_NEW.getValue(), groupId, sidList);
            }
        }
        stateData.setMaxGroupId(groupId);
        return stateData;
    }

    /**
     * 初始榷署
     */
    public void initOffice(){

        int activeNum = getGroupActiveNum();

        if(activeNum == 0){
            return;
        }

        if(Config.isDebug()) {
            List<MonopolyMarketOfficeSeatConfig> seatConfigList2 =
                    NewMonopolyMarketCommonMgr.calNewMonopolyMarketOfficeSeatConfigList(this.weekStateData.getServerIdList().size(),
                            activeNum,
                            CrossNewMonopolyMarketConfigMgr.getResConfigListByType(eMonopolyMarketResType.OFFICE_NEW.getValue()));
            CrossNewMonopolyMarketMgr.getLogger().info("测试：榷署数量：活跃玩家：{}", activeNum);
            for (MonopolyMarketOfficeSeatConfig seatConfig : seatConfigList2) {
                CrossNewMonopolyMarketMgr.getLogger().info("等级{}-数量{}", seatConfig.getLevel(), seatConfig.getEndIndex() - seatConfig.getStartIndex() + 1);
            }
        }

        boolean initSeatConfig = false;
        if(getMarketOffice().getSeatConfigList() == null || getMarketOffice().getSeatConfigList().size() == 0) {
            //榷署座位初始化
            List<MonopolyMarketOfficeSeatConfig> seatConfigList = NewMonopolyMarketCommonMgr.calNewMonopolyMarketOfficeSeatConfigList(this.weekStateData.getServerIdList().size(),
                    activeNum,
                    CrossNewMonopolyMarketConfigMgr.getResConfigListByType(eMonopolyMarketResType.OFFICE_NEW.getValue()));
            this.marketOffice.setSeatConfigList(seatConfigList);
            initSeatConfig = true;
        }

        if(getMarketOffice().getSeatDataMap() == null || getMarketOffice().getSeatDataMap().size() == 0) {
            Map<Integer, NewMonopolyMarketOfficeSeatInfo> seatDataMapTemp = new ConcurrentHashMap<>();
            for (MonopolyMarketOfficeSeatConfig seatConfig : getMarketOffice().getSeatConfigList()) {
                int i = seatConfig.getStartIndex();
                for (; i <= seatConfig.getEndIndex(); i++) {
                    NewMonopolyMarketOfficeSeatData seatData = new NewMonopolyMarketOfficeSeatData();
                    seatData.setWeekId(this.weekStateData.getWeekId());
                    seatData.setSystemGroupId(this.weekStateData.getSystemGroupId());
                    seatData.setSeatId(i);
                    seatData.setSeatLv(seatConfig.getLevel());
                    seatData.setInsertOption();
                    NewMonopolyMarketOfficeSeatInfo seatInfo = new NewMonopolyMarketOfficeSeatInfo(seatData);
                    seatDataMapTemp.put(seatData.getSeatId(), seatInfo);
                }
            }
            if(seatDataMapTemp.size() > 0){
                this.marketOffice.setSeatDataMap(seatDataMapTemp);
                this.marketOffice.updateAndAddSeatInfoSet.addAll(seatDataMapTemp.values());
            }
        }

        if(initSeatConfig) {
            //下发榷署位置信息
            NewMonopolyMarketProto.NewMonopolyMarketQueShuPointSync.Builder syncMsg = NewMonopolyMarketProto.NewMonopolyMarketQueShuPointSync.newBuilder();
            for (MonopolyMarketOfficeSeatConfig seatConfig : getMarketOffice().getSeatConfigList()) {
                NewMonopolyMarketProto.NewMonopolyMarketQueShuPointTemp.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketQueShuPointTemp.newBuilder();
                builder.setLevel(seatConfig.getLevel());
                builder.setRewardNum(seatConfig.getEndIndex() - seatConfig.getStartIndex() + 1);
                syncMsg.addPoint(builder);
            }
            for (Long sid : this.weekStateData.getServerIdList()) {
                MessageHelper.sendPacket(sid, 0, YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_QUE_SHU_POINT_SYNC, syncMsg));
            }
        }
    }

    /**
     * npc血量是否初始完毕
     */
    public boolean isNpcBloodInit(){
        if(this.weekStateData.getNpcBlood().size() == 0){
            return false;
        }
        for (Map.Entry<Integer, Map<Integer, Long>> mapEntry : this.weekStateData.getNpcBlood().entrySet()) {
            if(mapEntry.getValue().size() == 0){
                return false;
            }
        }
        return true;
    }

    /**
     * 活跃玩家数
     */
    public int getGroupActiveNum() {

        if(serverAbilityDataMap.size() != weekStateData.getServerIdList().size()){
            CrossNewMonopolyMarketMgr.getLogger().info("getGroupActiveNum serverAbilityDataMap size not equals server size");
            return 0;
        }

        if(weekStateData.getActiveNum() > 0){
            return weekStateData.getActiveNum();
        }

        //活跃人数
        int activeNum = 0;
        for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> entry : serverAbilityDataMap.entrySet()) {
            activeNum += entry.getValue().getActiveNum();
        }

        this.weekStateData.setActiveNum(activeNum);
        return activeNum;
    }

    /**
     * 初始npc血量
     */
    public void initNpcBlood() {

        int activeNum = getGroupActiveNum();

        if(activeNum == 0){
            CrossNewMonopolyMarketMgr.getLogger().info("initNpcBlood active num zero");
            return;
        }

        if(Config.isDebug()){
            //西夏
            for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> entry : serverAbilityDataMap.entrySet()) {
                for (NewMonopolyUserAbility userAbility : entry.getValue().getUserAbilityList()) {
//                    if(Config.isDebug()){
//                        CrossNewMonopolyMarketMgr.getLogger().info("西夏玩家{}-{}", userAbility.getU(), userAbility.getB());
//                    }
                }
            }

            //王帐
            for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> entry : serverAbilityDataMap.entrySet()) {
                for (NewMonopolyUserAbility userAbility : entry.getValue().getUserAbilityList()) {
//                    if(Config.isDebug()){
//                        CrossNewMonopolyMarketMgr.getLogger().info("王帐玩家{}-{}", userAbility.getU(), userAbility.getP());
//                    }
                }
            }
        }

        if(isNpcBloodInit()){
            return;
        }

        Map<Integer, Map<Integer, Long>> resNpcBloodMap = new HashMap<>();

        //王帐
        List<Long> allAbilityList = new LinkedList<>();
        for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> entry : serverAbilityDataMap.entrySet()) {
            for (NewMonopolyUserAbility userAbility : entry.getValue().getUserAbilityList()) {
                allAbilityList.addAll(userAbility.getP());
                if(Config.isDebug()){
                    CrossNewMonopolyMarketMgr.getLogger().info("玩家{}-{}", userAbility.getU(), userAbility.getP());
                }
            }
        }

        if(allAbilityList.size() == 0){
            return;
        }


        allAbilityList.sort(Comparator.reverseOrder());
        List<NewMonopolyMarketResConfigData> configDataList = CrossNewMonopolyMarketConfigMgr.getResConfigListByType(eMonopolyMarketResType.RES_KING_NEW.getValue());
        if(configDataList.size() == 0){
            CrossNewMonopolyMarketMgr.getLogger().info("initNpcBlood configDataList is null");
            return;
        }

        Map<Integer, Long> patronsBloodMap = new HashMap();
        for (NewMonopolyMarketResConfigData configData : configDataList) {
            long val = calAverage(allAbilityList, configData);
            patronsBloodMap.put(configData.getLevel(), val);
        }
        resNpcBloodMap.put(eMonopolyMarketResType.RES_KING_NEW.getValue(), patronsBloodMap);


        //西夏
        List<Long> allBeautyAbilityList = new LinkedList<>();
        for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> entry : serverAbilityDataMap.entrySet()) {
            for (NewMonopolyUserAbility userAbility : entry.getValue().getUserAbilityList()) {
                allBeautyAbilityList.addAll(userAbility.getB());
                if(Config.isDebug()){
                    CrossNewMonopolyMarketMgr.getLogger().info("玩家{}-{}", userAbility.getU(), userAbility.getB());
                }
            }
        }
        if(allBeautyAbilityList.size() == 0){
            return;
        }

        allBeautyAbilityList.sort(Comparator.reverseOrder());
        configDataList = CrossNewMonopolyMarketConfigMgr.getResConfigListByType(eMonopolyMarketResType.RES_QUEEN_NEW.getValue());

        Map<Integer, Long> beautyBloodMap = new HashMap();
        for (NewMonopolyMarketResConfigData configData : configDataList) {
            long val = calAverage(allBeautyAbilityList, configData);
            beautyBloodMap.put(configData.getLevel(), val);
        }
        resNpcBloodMap.put(eMonopolyMarketResType.RES_QUEEN_NEW.getValue(), beautyBloodMap);

        this.weekStateData.setNpcBlood(resNpcBloodMap);
    }

    public long getNpcBlood(int type, int level) {
        Map<Integer, Long> map = this.weekStateData.getNpcBlood().get(type);
        if(map == null || !map.containsKey(level)){
            return 0;
        }
        return map.get(level);
    }

    private long calAverage(List<Long> abilityList, NewMonopolyMarketResConfigData configData) {

        List<Long> paramList = StringUtils.stringToLongList(configData.getNpcList(), ";");

        int rank1 = (abilityList.size() * paramList.get(0).intValue() + 1000 - 1) / 1000;
        int rank2 = (abilityList.size() * paramList.get(1).intValue() + 1000 - 1) / 1000;

        long v1 = average(rank1, rank2, abilityList);

        int rank3 = paramList.get(2).intValue();
        int rank4 = paramList.get(3).intValue();

        long v2 = average(rank3, rank4, abilityList);

        long v3 = paramList.get(4);

        long v4 = paramList.get(5);

        long val = v1 > v2 ? v1 : v2;
        val = val > v3 ? val : v3;
        val = val > v4 ? val : v4;

        CrossNewMonopolyMarketMgr.getLogger().info("calAverage rank1 {},rank2 {},rank3 {},rank4 {},v1 {},v2 {},v3 {},v4 {},val {}",
                rank1, rank2, rank3, rank4, v1, v2, v3, v4, val);
        return val;
    }

    public long average(int rankStart, int rankEnd, List<Long> list){
        int num = 0;
        long all = 0;
        int size = list.size();
        for (int j = rankStart; j <= rankEnd; j++) {
            if (j > size) {
                break;
            }
            int index = j - 1;
            if (index < 0) {
                // 防止配0的情况
                continue;
            }
            all += list.get(index);
            num++;
        }
        long result = 0;
        if (num > 0) {
            result = (all + num - 1) / num;
        }
        return result;
    }

    public int getGroupNumByLevelAndType(int groupType, int resType){
        int num = 0;
        for (Map.Entry<Integer, ResourceServerGroup> groupEntry : this.weekStateData.getInnerGroupList().entrySet()) {
            ResourceServerGroup group = groupEntry.getValue();
            if(group.getResType() == resType && group.getGroupType() == groupType){
                num++;
            }
        }
        return num;
    }

    //加载数据
    public CrossNewMonopolyMarketGroup(NewMonopolyMarketWeekStateData weekStateData) {

        this.weekStateData = weekStateData;

        this.groupId = weekStateData.getSystemGroupId();

        this.marketOffice = new CrossNewMonopolyMarketOffice(this);

        this.marketResRob = new CrossNewMonopolyMarketResRob(this);
    }

    public void saveData(){

        if(this.weekStateData != null){
            if(weekStateData.isInsertOption()){
                new NewMonopolyMarketWeekStateDataDaoImpl().add(weekStateData);
            }else if(weekStateData.isUpdateOption()){
                new NewMonopolyMarketWeekStateDataDaoImpl().update(weekStateData);
            }
        }

        //玩家数据
        List<CrossNewMonopolyMarketUserData> tempUserDataList;
        synchronized (needAddServerUserDataList){
            tempUserDataList = new ArrayList<>(needAddServerUserDataList);
            needAddServerUserDataList.clear();
        }
        for (CrossNewMonopolyMarketUserData userData : tempUserDataList) {
            if(userData.isInsertOption()){
                new CrossNewMonopolyMarketUserDataDaoImpl().add(userData);
            }else if(userData.isUpdateOption()){
                new CrossNewMonopolyMarketUserDataDaoImpl().update(userData);
            }
        }

        //区服能力
        for (Map.Entry<Long, NewMonopolyMarketServerAbilityData> dataEntry : serverAbilityDataMap.entrySet()) {
            NewMonopolyMarketServerAbilityData data = dataEntry.getValue();
            if(data.isInsertOption()){
                new NewMonopolyMarketServerAbilityDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){

            }
        }

        getMarketOffice().saveData();

        getMarketResRob().saveData();

        // 保存公告
        List<NewMonopolyMarketNoticeData> tempList = new ArrayList<>();
        synchronized (needAddNoticeList) {
            tempList.addAll(needAddNoticeList);
            needAddNoticeList.clear();
        }
        for (NewMonopolyMarketNoticeData noticeData : tempList) {
            if (noticeData.isInsertOption()) {
                new NewMonopolyMarketNoticeDataDaoImpl().add(noticeData);
            }
        }
    }

    public void loadData() {

        //初始统计资源点占用的时间点
        if(weekStateData.getLastStatTime() == 0){
            int hourTime = getHourTime();
            weekStateData.setLastStatTime(hourTime);
        }

        //玩家数据
        serverUserDataMap = new CrossNewMonopolyMarketUserDataDaoImpl().getCrossNewMonopolyMarketUserData(weekStateData.getWeekId(), this.getGroupId());

        //区服能力
        serverAbilityDataMap = new NewMonopolyMarketServerAbilityDataDaoImpl().getNewMonopolyMarketServerAbilityData(weekStateData.getWeekId(), this.getGroupId());

        //加载榷署资源点
        this.getMarketOffice().loadData();

        //榷署座位初始化
        if(getGroupActiveNum() > 0) {
            List<MonopolyMarketOfficeSeatConfig> seatConfigList = NewMonopolyMarketCommonMgr.calNewMonopolyMarketOfficeSeatConfigList(this.weekStateData.getServerIdList().size(),
                    getGroupActiveNum(),
                    CrossNewMonopolyMarketConfigMgr.getResConfigListByType(eMonopolyMarketResType.OFFICE_NEW.getValue()));
            this.getMarketOffice().setSeatConfigList(seatConfigList);
        }

        //公告
        Map<Integer, List<NewMonopolyMarketNoticeData>> noticeDataMap = new NewMonopolyMarketNoticeDataDaoImpl().getNewMonopolyMarketNoticeData(weekStateData.getWeekId(), weekStateData.getSystemGroupId(), DateHelper.getTodayZeroTime());
        for (Map.Entry<Integer, List<NewMonopolyMarketNoticeData>> entry : noticeDataMap.entrySet()) {
            List<NewMonopolyMarketNoticeData> list = entry.getValue();
            int size = list.size();
            if(size <= CrossNewMonopolyMarketMgr.NOTICE_MAX_NUM){
                this.noticeMap.put(entry.getKey(), list);
            }else {
                this.noticeMap.put(entry.getKey(), new ArrayList<>(list.subList(size - CrossNewMonopolyMarketMgr.NOTICE_MAX_NUM, size)));
            }
        }

        userRankModel = new UserRankModel(getMaxRankCount(0, weekStateData.getOpenDays()));
        serverRankModel = new ServerRankModel(getMaxRankCount(1, weekStateData.getOpenDays()));

        //榜单
        LinkedList<UserRank> rankLinkedList = new LinkedList<>();
        LinkedList<ServerRank> serverRankLinkedList = new LinkedList<>();
        for (Map.Entry<Long, Map<Long, CrossNewMonopolyMarketUserData>> entry : serverUserDataMap.entrySet()) {
            long serverId = entry.getKey();
            ServerRank serverRank = new ServerRank();
            serverRank.setServerId(serverId);
            long lastUpdateTime = 0;
            long totalNum = 0;
            for (Map.Entry<Long, CrossNewMonopolyMarketUserData> userDataEntry : entry.getValue().entrySet()) {
                CrossNewMonopolyMarketUserData userData = userDataEntry.getValue();
                if(userData.getResGetNum() > 0){
                    totalNum += userData.getResGetNum();
                    if(userData.getLastUpdate() > lastUpdateTime){
                        lastUpdateTime = userData.getLastUpdate();
                    }

                    //
                    UserRank userRank = new UserRank();
                    userRank.setUserId(userData.getUserId());
                    userRank.setLastUpdateTime(userData.getLastUpdate());
                    userRank.setValue(BigInteger.valueOf(userData.getResGetNum()));
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userRank.getUserId());
                    if(userBaseInfo != null){
                        userRank.setUserBaseInfo(userBaseInfo);
                    }
                    rankLinkedList.add(userRank);
                }
            }
            serverRank.setLastUpdateTime(lastUpdateTime);
            serverRank.setValue(BigInteger.valueOf(totalNum));
            serverRankLinkedList.add(serverRank);
        }
        userRankModel.setRankList(rankLinkedList);
        serverRankModel.setRankList(serverRankLinkedList);

        //加载资源争夺
        this.getMarketResRob().loadData();

        this.initNpcBlood();
    }

    /**
     * 重置榷场数据
     */
    public void refreshMonopolyMarket(int anyInWeek, int now) {
        //每周的数据，榷署好像不用重置
        boolean success = this.getMarketOffice().refresh(anyInWeek, now);
        success = this.getMarketResRob().refresh(now) || success;
        if(success){
            // 系统结束 通知区服玩家重置数据
            NewMonopolyMarketProto.NewMonopolyMarketResetToGameServerMsg.Builder synMsg = NewMonopolyMarketProto.NewMonopolyMarketResetToGameServerMsg.newBuilder();
            synMsg.setBit(1);
            for (long serverId : this.getWeekStateData().getServerIdList()) {
                MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_NEW_MONOPOLY_MARKET_RESET_SYSTEM, synMsg));
            }
            CrossNewMonopolyMarketMgr.getLogger().info("group {}, 新榷场系统结束，通知区服玩家重置数据,bit:{}", 1, weekStateData.getSystemGroupId());
        }
    }

    /**
     * 登录同步配置
     */
    public void syncConfig(long serverId, long playerId) {

        NewMonopolyMarketProto.NewMonopolyMarketConfigRespMsg.Builder config = NewMonopolyMarketProto.NewMonopolyMarketConfigRespMsg.newBuilder();
        config.setOutSpeed(1000);
        // 分组配置
        NewMonopolyMarketProto.NewMonopolyMarketServerGroupEntity.Builder serverGroupEntity = NewMonopolyMarketProto.NewMonopolyMarketServerGroupEntity.newBuilder();
        serverGroupEntity.setGroupId(weekStateData.getSystemGroupId());
        serverGroupEntity.addAllServerList(weekStateData.getServerIdList());
        serverGroupEntity.setOpenDay(weekStateData.getOpenDays());
        serverGroupEntity.setWeekId(weekStateData.getWeekId());
        config.setServerGroupEntity(serverGroupEntity);

        //资源配置
        for(NewMonopolyMarketResConfigData item : CrossNewMonopolyMarketConfigMgr.getResConfigList()) {
            NewMonopolyMarketProto.NewMonopolyMarketResConfigEntity.Builder resConfigBuilder = CrossNewMonopolyMarketMgr.builderMonopolyMarketResConfigEntity(item);
            config.addResEntityList(resConfigBuilder);
        }

        //榷署资源点
        if(getMarketOffice().getSeatConfigList() != null){
            for (MonopolyMarketOfficeSeatConfig seatConfig : getMarketOffice().getSeatConfigList()) {
                NewMonopolyMarketProto.NewMonopolyMarketQueShuPointTemp.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketQueShuPointTemp.newBuilder();
                builder.setLevel(seatConfig.getLevel());
                builder.setRewardNum(seatConfig.getEndIndex() - seatConfig.getStartIndex() + 1);
                config.addPoint(builder);
            }
        }

        //榜单獎勵
        config.setUserRankReward(getSystemConfig(NewMonopolyMarketSystemConfigInfo.QUECHANG_REWARD_PERSON));
        config.setServerRankReward(getSystemConfig(NewMonopolyMarketSystemConfigInfo.QUECHANG_REWARD_SEVER));

        for (Map.Entry<Integer, ResourceServerGroup> entry : getWeekStateData().getInnerGroupList().entrySet()) {
            int resGroupId = entry.getKey();
            ResourceServerGroup serverGroup = entry.getValue();
            //大跨服据点，不过滤
            if(!serverGroup.getServerList().contains(serverId) && serverGroup.getGroupType() != 3){
                continue;
            }
            NewMonopolyMarketProto.NewMonopolyMarketTopResTemp.Builder topRes = NewMonopolyMarketProto.NewMonopolyMarketTopResTemp.newBuilder();
            topRes.setResGroupId(resGroupId);
            topRes.setResType(serverGroup.getResType());
            if(serverGroup.getServerList().size() == 0){
                topRes.addAllServerId(getWeekStateData().getServerIdList());
            }else {
                topRes.addAllServerId(serverGroup.getServerList());
            }
            topRes.setRangeType(serverGroup.getGroupType());

            NewMonopolyMarketResGrabMap item = getMarketResRob().getMarketResGrabMap().get(resGroupId).map;

            if(item != null){
                NewMonopolyMarketProto.NewMonopolyMarketResGrabMapEntity.Builder mapBuilder = NewMonopolyMarketProto.NewMonopolyMarketResGrabMapEntity.newBuilder();
                mapBuilder.setSide(item.side);
                mapBuilder.setType(item.type);
                mapBuilder.addAllLevel(item.indexLevelList);
                mapBuilder.setRealNum(item.realNum);
                topRes.setRedGrabMaps(mapBuilder);
            }else {
                CrossNewMonopolyMarketMgr.getLogger().info("========== map is null");
            }

            config.addTopRes(topRes);
        }

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_NEW_MONOPOLY_MARKET_SYN_CONFIG, config));
    }

    /**
     * 中心库系统配置
     */
    public String getSystemConfig(String key){
        // 加载后台配置
        int channelId = ConfigHelper.getInt("channelId");
        Map<String, ChannelSystemConfig> systemConfigMap = BattleChannelSystemConfigMgr.getSystemConfigMap(channelId, eSystemId.NewMonopolyMarket.getValue());
        if (systemConfigMap == null || !systemConfigMap.containsKey(key)) {
            return "";
        }
        return systemConfigMap.get(key).getValue();
    }

    /**
     * 获取玩家数据
     */
    public NewMonopolyMarketProto.NewMonopolyMarketCheckUserDataToGameServerMsg.Builder getUserData(long userId, long serverId, UserBaseInfo userBaseInfo, int decorationClass, int decorationOverTime) {
        NewMonopolyMarketProto.NewMonopolyMarketCheckUserDataToGameServerMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketCheckUserDataToGameServerMsg.newBuilder();
        builder.setUserId(userId);

        synchronized (getMarketOffice()) {
            // 校验榷署位置
            NewMonopolyMarketOfficeSeatInfo seatInfo = getMarketOffice().userSeatMap.get(userId);
            if (seatInfo != null) {
                // 同步位置数据
                CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo);
                seatInfo.baseInfo.setDecorationOverTime(decorationOverTime);
                seatInfo.baseInfo.setDecorationClass((byte) decorationClass);
                synchronized (getMarketOffice().updateAndAddSeatInfoSet) {
                    getMarketOffice().updateAndAddSeatInfoSet.add(seatInfo);
                }
                int level = NewMonopolyMarketCommonMgr.calOfficePosLevel(getMarketOffice().seatConfigList, seatInfo.baseInfo.getSeatId());
                builder.setOfficePosIndex(seatInfo.baseInfo.getSeatId());
                builder.setOfficePosLevel(level);
                builder.setOfficePosNo(getMarketOffice().calNo(seatInfo.baseInfo.getSeatId()));
                builder.setOfficeSeatTime(seatInfo.baseInfo.getSeatId());
            } else {
                NewMonopolyMarketOfficeFinishData finishData = getMarketOffice().userOfficeFinishMap.remove(userId);
                if (finishData != null) {
                    NewMonopolyMarketProto.NewMonopolyMarketOfficeRobedRecordEntity.Builder robedRecord = NewMonopolyMarketProto.NewMonopolyMarketOfficeRobedRecordEntity.newBuilder();
                    robedRecord.setPosIndex(finishData.getPosIndex());
                    robedRecord.setLevel(finishData.getLevel());
                    robedRecord.setNo(finishData.getNo());
                    robedRecord.setTime(finishData.getTime());
                    robedRecord.setName(finishData.getRobName());
                    finishData.setIsSyn(true);
                    builder.setRobedRecord(robedRecord);
                    synchronized (getMarketOffice().tempOfficeFinishList) {
                        getMarketOffice().tempOfficeFinishList.add(finishData);
                    }
                    builder.setHasTip(true);
                }
                builder.setOfficePosIndex(-1);
            }
        }

        synchronized (getMarketResRob()) {
            for (NewMonopolyMarketResGrab item : getMarketResRob().getMarketResGrabMap().values()) {
                // 下发正在采集的对象
                Set<NewMonopolyMarketResGrabPointInfo> pointInfos = item.getUserPointSet(userId, false);
                if (pointInfos != null) {
                    for (NewMonopolyMarketResGrabPointInfo pointInfo : pointInfos) {
                        if (pointInfo.baseInfo.getUserId() != userId) {
                            continue;
                        }
                        NewMonopolyMarketProto.NewMonopolyMarketSynDispatchInfoEntity.Builder synDispatchInfo = NewMonopolyMarketProto.NewMonopolyMarketSynDispatchInfoEntity.newBuilder();
                        synDispatchInfo.setResGroupId(pointInfo.baseInfo.getResGroupId());
                        synDispatchInfo.setType(pointInfo.baseInfo.getType());
                        synDispatchInfo.setPosIndex(pointInfo.baseInfo.getPosIndex());
                        synDispatchInfo.setStartTime(pointInfo.baseInfo.getSeatTime());
                        synDispatchInfo.addAllDispatchObjectId(pointInfo.objectInfoMap.keySet());
                        builder.addDispatchInfoList(synDispatchInfo);
                    }
                }
            }
            // 是否有资源点结算弹窗
            List<NewMonopolyMarketResGrabFinishData> resRewardList = getMarketResRob().userResGrabFinishMap.get(userId);
            if ((resRewardList != null && resRewardList.size() > 0)) {
                builder.setHasTip(true);
            }
        }

        CrossNewMonopolyMarketUserData userData = getNewMonopolyMarketUserData(serverId, userId, false);
        if(userData != null){
            builder.setGetUserReward(userData.isGetUserReward());
            builder.setGetServerReward(userData.isGetServerReward());
        }

        return builder;
    }

    //进入榷场  尝试领取奖励  下发资源信息
    public NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.Builder enter(long serverId, long playerId, int groupId) {
        NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.newBuilder();
        // 资源战
        List<NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg> settlementList = getMarketResRob().receiveRewardList(playerId);
        builder.addAllPointSettlementList(settlementList);
        return builder;
    }

    /**
     * 尝试退出 所进入过的位置、据点
     * @param userId
     */
    public void exitAllSeat(long userId) {
        // 离开榷署房间
        int officePosIndex = marketOffice.userInRoomMap.getOrDefault(userId, 0);
        marketOffice.exitOfficeSeat(officePosIndex, userId);

        // 离开资源点
        marketResRob.exitAllSeat(userId);
    }

    /**
     * 获取队伍信息
     *
     * @param userId
     * @param serverId
     */
    public NewMonopolyMarketProto.NewMonopolyMarketGetTeamRespMsg.Builder getTeamList(long userId, long serverId, int type) {
        NewMonopolyMarketProto.NewMonopolyMarketGetTeamRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketGetTeamRespMsg.newBuilder();
        List<Integer> resGroupList = getServerResGroupId(serverId, type);
//        synchronized (marketResRob) {
            for (int id : resGroupList) {
                NewMonopolyMarketResGrab resGrab = marketResRob.getMarketResGrabMap().get(id);
                if(resGrab != null){
                    Set<NewMonopolyMarketResGrabPointInfo> set = resGrab.getUserPointSet(userId,false);
                    if(set != null){
                        for (NewMonopolyMarketResGrabPointInfo pointInfo : set){
                            if(pointInfo.baseInfo.getUserId() != userId){
                                continue;
                            }
                            builder.addTeamList(marketResRob.builderMonopolyMarketGetTeamEntity(pointInfo));
                        }
                    }
                }
            }
//        }
        builder.setRet(0);
        return builder;
    }

    public List<Integer> getServerResGroupId(long serverId, int type){
        List<Integer> list = new ArrayList<>();
        for (Map.Entry<Integer, ResourceServerGroup> entry : this.weekStateData.getInnerGroupList().entrySet()) {
            if(type > 0 && entry.getValue().getResType() != type){
                continue;
            }
            if(entry.getValue().getServerList().size() == 0){
                list.add(entry.getKey());
            }else if(entry.getValue().getServerList().contains(serverId)){
                list.add(entry.getKey());
            }
        }
        return list;
    }

    /**
     * 领取奖励
     */
    public NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.Builder receiveReward(long userId){
        NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketEnterRespMsgToGameServerMsg.newBuilder();
        List<NewMonopolyMarketProto.NewMonopolyMarketSynPointSettlementToGameServerMsg> settlementList = getMarketResRob().receiveRewardList(userId);
        builder.addAllPointSettlementList(settlementList);
        return builder;
    }

    public void addNotice(int type, long attackerId, long defenderId, int pos, int resGroupId, int actionType, int occupyType) {
        NewMonopolyMarketNoticeData noticeData = initNewMonopolyMarketNoticeData(type, attackerId, defenderId, pos, resGroupId, actionType, occupyType);
        addNotice(noticeData);
    }

    public void addNotice(NewMonopolyMarketNoticeData noticeData) {
        List<NewMonopolyMarketNoticeData> list = noticeMap.get(noticeData.getResGroupId());
        if (list == null) {
            list = new ArrayList<>();
            noticeMap.put(noticeData.getResGroupId(), list);
        }
        while (list.size() >= CrossNewMonopolyMarketMgr.NOTICE_MAX_NUM) {
            list.remove(0);
        }
        list.add(noticeData);
        synchronized (needAddNoticeList) {
            needAddNoticeList.add(noticeData);
        }
        // 广播
        NewMonopolyMarketProto.NewBroadcastMonopolyMarketRespMsg.Builder noticeBroadcast = NewMonopolyMarketProto.NewBroadcastMonopolyMarketRespMsg.newBuilder();
        noticeBroadcast.setNewNotice(builderMonopolyMarketNoticeEntity(noticeData));
        // 区服范围
        List<Long> serverList = getWeekStateData().getServerIdList();
        if(noticeData.getResGroupId() > 0){
            ResourceServerGroup serverGroup = getWeekStateData().getInnerGroupList().get(noticeData.getResGroupId());
            if(serverGroup.getServerList().size() > 0){
                serverList = serverGroup.getServerList();
            }
        }
        for (long serverId : serverList) {
            noticeBroadcast.setType(4);
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_NEW_MONOPOLY_MARKET_NOTICE_BROADCAST_FROM_CROSS, noticeBroadcast));
        }
    }

    public NewMonopolyMarketNoticeData initNewMonopolyMarketNoticeData(int type, long attackerId, long defenderId, int pos, int resGroupId, int actionType, int occupyType) {
        NewMonopolyMarketNoticeData noticeData = new NewMonopolyMarketNoticeData();
        noticeData.setInsertOption();
        noticeData.setWeekId(weekStateData.getWeekId());
        noticeData.setGroupId(weekStateData.getSystemGroupId());
        noticeData.setType(type);
        noticeData.setResGroupId(resGroupId);
        noticeData.setUserId(attackerId);
        noticeData.setPos(pos);
        noticeData.setTime(DateHelper.getCurrentSecond());
        noticeData.setRobedId(defenderId);
        noticeData.setActionType(actionType);
        noticeData.setOccupyType(occupyType);
        return noticeData;
    }

    /**
     * 获取最新的公告
     *
     * @return
     */
    public NewMonopolyMarketNoticeData getNewMonopolyMarketNoticeData(int resGroupId, long serverId) {
        NewMonopolyMarketNoticeData newNotice = null;
        List<NewMonopolyMarketNoticeData> list = noticeMap.get(resGroupId);
        if (list != null && list.size() > 0) {
            newNotice = list.get(list.size() - 1);
        }
        return newNotice;
    }

    /**
     * 查看榷场公告
     *
     * @param type     11榷署 12 王帐  13 王宫
     * @param serverId
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketGetNoticeRespMsg.Builder getNotice(int type, int page, long serverId) {
        NewMonopolyMarketProto.NewMonopolyMarketGetNoticeRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketGetNoticeRespMsg.newBuilder();
        List<NewMonopolyMarketNoticeData> noticeTempList = new ArrayList<>();
        if(type == eMonopolyMarketResType.OFFICE_NEW.getValue()){
            if(noticeMap.containsKey(0)){
                noticeTempList.addAll(noticeMap.get(0));
            }
        }else {
            for (Map.Entry<Integer, ResourceServerGroup> groupEntry : weekStateData.getInnerGroupList().entrySet()) {
                if(groupEntry.getValue().getResType() != type){
                    continue;
                }
                if(noticeMap.containsKey(groupEntry.getKey())){
                    noticeTempList.addAll(noticeMap.get(groupEntry.getKey()));
                }
            }
        }
        for (NewMonopolyMarketNoticeData item : noticeTempList) {
            builder.addNoticeList(builderMonopolyMarketNoticeEntity(item));
        }
        builder.setRet(0);
        return builder;
    }

    public void syncInnerGroup(long serverId, int weekId) {
        if(weekStateData.getWeekId() != weekId){
            return;
        }
        NewMonopolyMarketProto.NewMonopolyMarketInnerGroupSync.Builder syncMsg = NewMonopolyMarketProto.NewMonopolyMarketInnerGroupSync.newBuilder();
        syncMsg.setWeekId(weekId);
        for (Map.Entry<Integer, ResourceServerGroup> entry : weekStateData.getInnerGroupList().entrySet()) {
            NewMonopolyMarketProto.NewMonopolyMarketInnerGroupTemp.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketInnerGroupTemp.newBuilder();
            ResourceServerGroup serverGroup = entry.getValue();
            builder.setGroupId(serverGroup.getGroupId());
            builder.setGroupType(serverGroup.getGroupType());
            builder.setResType(serverGroup.getResType());
            if(serverGroup.getServerList().size() == 0){
                builder.addAllServerId(weekStateData.getServerIdList());
            }else {
                if(!serverGroup.getServerList().contains(serverId)){
                    continue;
                }
                builder.addAllServerId(serverGroup.getServerList());
            }
            syncMsg.addGroup(builder);
        }
        if(syncMsg.getGroupCount() > 0){
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_CROSS_NEW_MONOPOLY_MARKET_SYNC_INNER_GROUP_FROM_CROSS, syncMsg));
        }
    }

    /**
     * 上报区服能力
     * @param serverId 区服
     * @param abilityMsg 玩家能力
     * @return
     */
    public NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityRespMsg.Builder uploadServerAbility(long serverId, NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityMsg abilityMsg){

        Calendar calendar = Calendar.getInstance();
        if(calendar.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY && !Config.isDebug() && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){
            return NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityRespMsg.newBuilder().setZeroTime(0);
        }

        NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityRespMsg.newBuilder();
        builder.setZeroTime(abilityMsg.getZeroTime());
        NewMonopolyMarketServerAbilityData serverAbilityData = serverAbilityDataMap.get(serverId);
        if(serverAbilityData == null){
            synchronized (serverAbilityDataMap){
                serverAbilityData = serverAbilityDataMap.get(serverId);
                if(serverAbilityData == null){
                    serverAbilityData = new NewMonopolyMarketServerAbilityData();
                    serverAbilityData.setInsertOption();
                    serverAbilityData.setGroupId(getGroupId());
                    serverAbilityData.setServerId(serverId);
                    serverAbilityData.setWeekId(getWeekStateData().getWeekId());
                    serverAbilityDataMap.put(serverId, serverAbilityData);
                }else {
                    return builder;
                }
            }
        }else {
            return builder;
        }
        if(serverAbilityData.getResetTime() < abilityMsg.getZeroTime()){
            serverAbilityData.setResetTime(abilityMsg.getZeroTime());
            List<NewMonopolyUserAbility> userAbilityList = new ArrayList<>();
            for (NewMonopolyMarketProto.NewMonopolyMarketUserAbilityTemp abilityTemp : abilityMsg.getAbilityList()) {
                NewMonopolyUserAbility userAbility = new NewMonopolyUserAbility();
                userAbility.setU(abilityTemp.getUserId());
                userAbility.setB(abilityTemp.getBeautyAbilityList());
                userAbility.setP(abilityTemp.getPatronsAbilityList());
                userAbilityList.add(userAbility);
            }
            serverAbilityData.setActiveNum(userAbilityList.size());
            serverAbilityData.setUserAbilityList(userAbilityList);
        }

        //测试环境，初始其他区服能力
        if(Config.isDebug() && (serverId == 99938028 || serverId == 99908193)){
            for (long sid : getWeekStateData().getServerIdList()) {
                if(sid != serverId){
                    uploadServerAbility(sid, abilityMsg);
                }
            }
        }
        return builder;
    }

    public void checkActiveUserUploadAbility(){

        Calendar calendar = Calendar.getInstance();
        if(calendar.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY && calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY){
            return;
        }
        List<Long> idList = new ArrayList<>(this.weekStateData.getServerIdList());
        idList.removeAll(serverAbilityDataMap.keySet());
        if(idList.size() > 0) {
            CrossNewMonopolyMarketMgr.getLogger().info("等待区服上报玩家队伍，{}", idList);

            NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityNotifyMsg.Builder notify = NewMonopolyMarketProto.NewMonopolyMarketUploadAbilityNotifyMsg.newBuilder();
            for (Long sid : idList) {
                MessageHelper.sendPacket(sid, 0, YanQuMessageUtils.buildMessage(Protocol.S_CROSS_NEW_MONOPOLY_MARKET_UPLOAD_SERVER_ABILITY_FROM_CROSS, notify));
            }
        }
    }

    /**
     *
     */
    public NewMonopolyMarketProto.NewMonopolyMarketGetRankRewardRespMsg.Builder getUserRankReward(long serverId, long userId, int type) {
        NewMonopolyMarketProto.NewMonopolyMarketGetRankRewardRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketGetRankRewardRespMsg.newBuilder();
        builder.setType(type);

        String reward;
        CrossNewMonopolyMarketUserData userData = getNewMonopolyMarketUserData(serverId, userId, false);
        if(userData == null && type == 0){
            builder.setRet(GameErrorCode.E_SYSTEM_NO_OPEN);
            return builder;
        }
        int openDays = weekStateData.getOpenDays();
        String configReward = getRewardConfig(type, openDays);
        if(StringUtils.isNullOrEmpty(configReward)){
            builder.setRet(GameErrorCode.E_ERROR_DATA);
            return builder;
        }
        if(type == 0){
            if(userData.isGetUserReward()){
                builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_REWARD_HAD_GET);
                return builder;
            }
            int myRank = userRankModel.getMyRank(userId);
            reward = getRandReward(myRank, configReward);
            if(StringUtils.isNullOrEmpty(reward)){
                builder.setRet(-1);
                return builder;
            }
            userData.setGetUserReward(true);
            addUserDataUpdate(userData);
            builder.setReward(reward);
        }else {
            if(userData != null && userData.isGetServerReward()){
                builder.setRet(GameErrorCode.E_NEW_MONOPOLY_MARKET_REWARD_HAD_GET);
                return builder;
            }
            int myRank = serverRankModel.getMyRank(serverId);
            reward = getRandReward(myRank, configReward);
            if(StringUtils.isNullOrEmpty(reward)){
                builder.setRet(-1);
                return builder;
            }
            if(userData != null) {
                userData.setGetServerReward(true);
                addUserDataUpdate(userData);
            }
            builder.setReward(reward);
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 锁名单
     * @param now
     */
    public void lockRank(int now){
        //时间
        if(NewMonopolyMarketCommonMgr.inWeekSettlementTime(this.weekStateData.getOfficeRefreshTime(), now)){

            if(weekStateData.isBattleEndHandle()){
                return;
            }

            int num = 1;
            for (UserRank userRank : userRankModel.getRankList()) {
                LogNewMonopolyMarketRank rank = new LogNewMonopolyMarketRank(this.getWeekStateData().getWeekId(), this.weekStateData.getSystemGroupId(),
                        userRank.getUserId(), 1, num, userRank.getValue().longValue(), new Date(userRank.getLastUpdateTime() * 1000));
                num++;
                CrossAutoLogMgr.add(rank);
            }

            num = 1;
            for (ServerRank serverRank : serverRankModel.getRankList()) {
                LogNewMonopolyMarketRank rank = new LogNewMonopolyMarketRank(this.getWeekStateData().getWeekId(), this.weekStateData.getSystemGroupId(),
                        serverRank.getServerId(), 2, num, serverRank.getValue().longValue(), new Date(serverRank.getLastUpdateTime() * 1000));
                num++;
                CrossAutoLogMgr.add(rank);
            }

            weekStateData.setBattleEndHandle(true);
        }
    }

    private String getRandReward(int rank, String rewardConfig){
        List<String> rankRewardList = StringUtils.stringToStringList(rewardConfig, "#");
        for (String rankRewardParam : rankRewardList) {
            List<String> list = StringUtils.stringToStringList(rankRewardParam, "-");
            int startRank = Integer.parseInt(list.get(0));
            int endRank = Integer.parseInt(list.get(1));
            if(rank >= startRank && rank <= endRank){
                return list.get(2);
            }
        }
        return "";

    }

    public int getMaxRankCount(int type, int openDays){
        String configReward = getRewardConfig(type, openDays);
        List<String> rankRewardList = StringUtils.stringToStringList(configReward, "#");
        if(rankRewardList.size() == 0){
            return 200;
        }
        List<String> paramList = StringUtils.stringToStringList(rankRewardList.get(rankRewardList.size() -1), "-");
        return Integer.parseInt(paramList.get(1));
    }

    public String getRewardConfig(int type, int openDays){
        String config;
        if(type == 0){
            config = getSystemConfig(NewMonopolyMarketSystemConfigInfo.QUECHANG_REWARD_PERSON);
        }else {
            config = getSystemConfig(NewMonopolyMarketSystemConfigInfo.QUECHANG_REWARD_SEVER);
        }
        if(StringUtils.isNullOrEmpty(config)){
            return "";
        }
        String openDaysConfig = "";
        List<String> openDaysConfigList = StringUtils.stringToStringList(config, "\\|");
        for (String param : openDaysConfigList) {
            List<String> daysConfigList = StringUtils.stringToStringList(param, ":");
            if(StringUtils.isNullOrEmpty(openDaysConfig)){
                openDaysConfig = daysConfigList.get(1);
            }
            int days = Integer.parseInt(daysConfigList.get(0));
            if(openDays >= days){
                openDaysConfig = daysConfigList.get(1);
            }
        }
        return openDaysConfig;
    }

    public void autoRewardTask() {
        //时间
        int weekId = GameConfig.getSystemThisWeekId();
        if(weekId <= weekStateData.getWeekId() || weekId - weekStateData.getWeekId() != 7){
            return;
        }

        //先锁榜单
        if(!weekStateData.isBattleEndHandle()){
            return;
        }

        if(weekStateData.isRankReward()){
            return;
        }

        weekStateData.setRankReward(true);

        CrossNewMonopolyMarketMgr.getLogger().info("奖励补发：weekId {} ,groupId {}", weekStateData.getWeekId(), weekStateData.getSystemGroupId());

        int num = 0;
        Map<Long, Map<Long, Integer>> sererUserMap = new HashMap<>();
        for (UserRank userRank : userRankModel.getRankList()) {
            num++;
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userRank.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            long serverId = userBaseInfo.getServerId();
            CrossNewMonopolyMarketUserData userData = getNewMonopolyMarketUserData(serverId, userRank.getUserId(), false);
            if(userData == null || userData.isGetUserReward()){
                continue;
            }
            userData.setGetUserReward(true);
            addUserDataUpdate(userData);
            if(!sererUserMap.containsKey(serverId)){
                sererUserMap.put(serverId, new HashMap<>());
            }
            sererUserMap.get(serverId).put(userRank.getUserId(), num);
        }

        String rewardConfig = getRewardConfig(0, weekStateData.getOpenDays());
        if(StringUtils.isNullOrEmpty(rewardConfig)){
            CrossNewMonopolyMarketMgr.getLogger().info("奖励补发：weekId {} ,groupId {}, 开服天数 {} 的奖励未配置", weekStateData.getWeekId(), weekStateData.getSystemGroupId(), weekStateData.getOpenDays());
            return;
        }
        for (Map.Entry<Long, Map<Long, Integer>> entry : sererUserMap.entrySet()) {
            long serverId = entry.getKey();
            NewMonopolyMarketProto.NewMonopolyMarketAutoSendRewardSync.Builder syncBuild = NewMonopolyMarketProto.NewMonopolyMarketAutoSendRewardSync.newBuilder();
            syncBuild.setType(0);
            for (Map.Entry<Long, Integer> integerEntry : entry.getValue().entrySet()) {
                long userId = integerEntry.getKey();
                String reward = getRandReward(integerEntry.getValue(), rewardConfig);
                NewMonopolyMarketProto.NewMonopolyMarketAutoSendReward.Builder rankBuild = NewMonopolyMarketProto.NewMonopolyMarketAutoSendReward.newBuilder();
                rankBuild.setRank(integerEntry.getValue());
                rankBuild.setUserId(userId);
                rankBuild.setReward(reward);
                syncBuild.addRank(rankBuild);
            }
            CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} auto send user rank reward server {} siz {}", weekStateData.getWeekId(), weekStateData.getSystemGroupId(),
                    serverId, syncBuild.getRankCount());
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_AUTO_SEND_RANK_REWARD_FROM_CROSS, syncBuild));
        }

        //区服奖励
//        String serverRankRewardConfig = getRewardConfig(1, weekStateData.getOpenDays());
//        for (Map.Entry<Long, Map<Long, CrossNewMonopolyMarketUserData>> entry : serverUserDataMap.entrySet()) {
//            long serverId = entry.getKey();
//            int rank = serverRankModel.getMyRank(serverId);
//            String reward = getRandReward(rank, serverRankRewardConfig);
//            NewMonopolyMarketProto.NewMonopolyMarketAutoSendRewardSync.Builder syncBuild = NewMonopolyMarketProto.NewMonopolyMarketAutoSendRewardSync.newBuilder();
//            syncBuild.setType(0);
//            for (Map.Entry<Long, CrossNewMonopolyMarketUserData> dataEntry : entry.getValue().entrySet()) {
//                long userId = dataEntry.getKey();
//                CrossNewMonopolyMarketUserData userData = getNewMonopolyMarketUserData(serverId, userId,false);
//                if(userData == null || userData.isGetServerReward()){
//                    continue;
//                }
//                userData.setGetServerReward(true);
//                addUserDataUpdate(userData);
//                NewMonopolyMarketProto.NewMonopolyMarketAutoSendReward.Builder rankBuild = NewMonopolyMarketProto.NewMonopolyMarketAutoSendReward.newBuilder();
//                rankBuild.setRank(rank);
//                rankBuild.setUserId(userId);
//                rankBuild.setReward(reward);
//                syncBuild.addRank(rankBuild);
//            }
//            CrossNewMonopolyMarketMgr.getLogger().info("weekId {} groupId {} auto send user server rank reward server {} siz {}", weekStateData.getWeekId(), weekStateData.getSystemGroupId(),
//                    serverId, syncBuild.getRankCount());
//            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_NEW_MONOPOLY_MARKET_AUTO_SEND_RANK_REWARD_FROM_CROSS, syncBuild));
//        }

    }

    public void chat(WorldMessageProto.WorldMessageTempMsg chatMsg){
        synchronized (chatListMsg) {
            if (chatListMsg.getDataListCount() >= CrossNewMonopolyMarketMgr.MAX_MESSAGE_COUNT) {
                chatListMsg.removeDataList(0);
            }
            chatListMsg.addDataList(chatMsg);
        }

        // 转发聊天到游戏服
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_WORLD_MESSAGE_TRANSFER, chatMsg);
        for (long serverId : weekStateData.getServerIdList()) {
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public WorldMessageProto.WorldMessageListMsg.Builder getChatListMsg(){
        return chatListMsg;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketNoticeEntity.Builder builderMonopolyMarketNoticeEntity(NewMonopolyMarketNoticeData item) {
        NewMonopolyMarketProto.NewMonopolyMarketNoticeEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketNoticeEntity.newBuilder();
        builder.setType(item.getType());
        builder.setRobId(item.getUserId());
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(item.getUserId());
        if (userBaseInfo != null) {
            builder.setRobInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        }
        builder.setPosIndex(item.getPos());
        if (item.getRobedId() > 0) {
            UserBaseInfo robedUserInfo = CrossUserMgr.getUserBaseInfo(item.getRobedId());
            if (robedUserInfo != null) {
                builder.setRobedName(robedUserInfo.getNickName());
            }
        }
        builder.setTime(item.getTime());
        builder.setResGroupId(item.getResGroupId());
        builder.setActionType(item.getActionType());
        builder.setOccupyType(item.getOccupyType());
        return builder;
    }

    public static List<NewMonopolyMarketBaseBattleObjectInfo> formatPatronsList(List<NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity> patronsList){
        List<NewMonopolyMarketBaseBattleObjectInfo> list = new ArrayList<>();
        for (NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity item : patronsList){
            NewMonopolyMarketPatronsInfo patronsInfo = new NewMonopolyMarketPatronsInfo();
            patronsInfo.setId(item.getPatronsId());
            patronsInfo.setLevel(item.getLevel());
            patronsInfo.setStageLv(item.getStageLv());
            patronsInfo.setSkinId(item.getSkinId());
            patronsInfo.setBase(item.getEarn());
            patronsInfo.setAddition(item.getAddPlus());
            patronsInfo.setPromotionId(item.getPromotionId());
            patronsInfo.setTotalBlood(item.getEarn());
            patronsInfo.setBlood(item.getEarn());
            list.add(patronsInfo);
        }
        return list;
    }
    public static List<NewMonopolyMarketBaseBattleObjectInfo> formatBeautyList(List<NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity> beautyList){
        List<NewMonopolyMarketBaseBattleObjectInfo> list = new ArrayList<>();
        for (NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity item : beautyList){
            NewMonopolyMarketBeautyInfo patronsInfo = new NewMonopolyMarketBeautyInfo();
            patronsInfo.setId(item.getId());
            patronsInfo.setBase(item.getValue());
            patronsInfo.setSkinId(item.getSkinId());
            patronsInfo.setAddition(item.getAddPlus());
            patronsInfo.setTotalBlood(item.getValue());
            patronsInfo.setBlood(item.getValue());
            list.add(patronsInfo);
        }
        return list;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity.Builder builderMonopolyMarketPatronsEntity(NewMonopolyMarketPatronsInfo patronsInfo){
        NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketPatronsEntity.newBuilder();
        builder.setPatronsId(patronsInfo.getId());
        builder.setLevel(patronsInfo.getLevel());
        builder.setStageLv(patronsInfo.getStageLv());
        builder.setSkinId(patronsInfo.getSkinId());
        builder.setEarn(patronsInfo.getBase());
        builder.setAddPlus(patronsInfo.getAddition());
        builder.setPromotionId(patronsInfo.getPromotionId());
        return builder;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity.Builder builderMonopolyMarketBeautyEntity(NewMonopolyMarketBeautyInfo beautyInfo){
        NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketBeautyEntity.newBuilder();
        builder.setId(beautyInfo.getId());
        builder.setSkinId(beautyInfo.getSkinId());
        builder.setValue(beautyInfo.getBase());
        builder.setAddPlus(beautyInfo.getAddition());
        return builder;
    }

    //---------

    public ResourceServerGroup getResourceServerGroup(int resGroupId){
        return weekStateData.getInnerGroupList().get(resGroupId);
    }

    public void changeUserRank(CrossNewMonopolyMarketUserData userData){

        UserRank userRank = new UserRank();
        userRank.setLastUpdateTime(userData.getLastUpdate());
        userRank.setParam("");
        userRank.setUserId(userData.getUserId());
        userRank.setValue(BigInteger.valueOf(userData.getResGetNum()));
        userRank.setUserBaseInfo(CrossUserMgr.getUserBaseInfo(userData.getUserId()));
        userRankModel.rankChange(userRank);

        Map<Long, CrossNewMonopolyMarketUserData> userMap = serverUserDataMap.get(userData.getServerId());

        if(userMap != null){
            long maxTime = 0;
            long total = 0;
            for (Map.Entry<Long, CrossNewMonopolyMarketUserData> entry : userMap.entrySet()) {
                CrossNewMonopolyMarketUserData ud = entry.getValue();
                total+= ud.getResGetNum();
                if(ud.getLastUpdate() > maxTime){
                    maxTime = ud.getLastUpdate();
                }
            }
            ServerRank serverRank = new ServerRank();
            serverRank.setLastUpdateTime(maxTime);
            serverRank.setServerId(userData.getServerId());
            serverRank.setValue(BigInteger.valueOf(total));
            serverRankModel.rankChange(serverRank);
        }

    }

    //get method
    public int getGroupId() {
        return groupId;
    }

    public NewMonopolyMarketWeekStateData getWeekStateData() {
        return weekStateData;
    }

    public CrossNewMonopolyMarketOffice getMarketOffice() {
        return marketOffice;
    }

    public CrossNewMonopolyMarketResRob getMarketResRob() {
        return marketResRob;
    }

    public Map<Integer, List<NewMonopolyMarketNoticeData>> getNoticeMap() {
        return noticeMap;
    }

    public List<NewMonopolyMarketNoticeData> getNeedAddNoticeList() {
        return needAddNoticeList;
    }

    public Map<Long, NewMonopolyMarketServerAbilityData> getServerAbilityDataMap() {
        return serverAbilityDataMap;
    }

    public CrossNewMonopolyMarketUserData getNewMonopolyMarketUserData(long serverId, long userId, boolean newIfNull){
        if(serverId == 0){
            return null;
        }
        Map<Long, CrossNewMonopolyMarketUserData> userDataMap = serverUserDataMap.get(serverId);
        if(userDataMap == null){
            synchronized (serverUserDataMap){
                userDataMap = serverUserDataMap.get(serverId);
                if(userDataMap == null){
                    userDataMap = new ConcurrentHashMap<>();
                    serverUserDataMap.put(serverId, userDataMap);
                }
            }
        }
        CrossNewMonopolyMarketUserData userData = userDataMap.get(userId);
        if(userData == null && newIfNull){
            boolean change = false;
            synchronized (userDataMap){
                userData = userDataMap.get(userId);
                if(userData == null){
                    userData = new CrossNewMonopolyMarketUserData();
                    userData.setWeekId(this.getWeekStateData().getWeekId());
                    userData.setInsertOption();
                    userData.setGroupId(this.getWeekStateData().getSystemGroupId());
                    userData.setUserId(userId);
                    userData.setServerId(serverId);
                    userDataMap.put(userId, userData);
                    change = true;
                }
            }
            if(change){
                addUserDataUpdate(userData);
            }
        }
        return userData;
    }

    public void addUserDataUpdate(CrossNewMonopolyMarketUserData userData) {
        synchronized (needAddServerUserDataList){
            needAddServerUserDataList.add(userData);
        }
    }

    public Map<Long, Map<Long, CrossNewMonopolyMarketUserData>> getServerUserDataMap() {
        return serverUserDataMap;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketUserRankListRespMsg.Builder getUserRankList(long serverId, long playerId) {
        NewMonopolyMarketProto.NewMonopolyMarketUserRankListRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketUserRankListRespMsg.newBuilder();

        RankProto.RankListMsg.Builder listBuilder = RankProto.RankListMsg.newBuilder();
        for (UserRank userRank : userRankModel.getRankList()) {
            RankProto.RankTempMsg.Builder ur = RankProto.RankTempMsg.newBuilder();
            ur.setUserId(userRank.getUserId());
            ur.setParam(userRank.getParam());
            ur.setValue(userRank.getValue().toString());
            if(userRank.getUserBaseInfo() != null) {
                ur.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userRank.getUserBaseInfo()));
            }else {
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userRank.getUserId());
                if(userBaseInfo != null){
                    ur.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }
            }
            listBuilder.addRankList(ur);
        }
        builder.setMyRank(-1);
        builder.setMyValue("0");

        CrossNewMonopolyMarketUserData userData = getNewMonopolyMarketUserData(serverId, playerId, false);
        if(userData != null){
            builder.setMyValue(String.valueOf(userData.getResGetNum()));
            builder.setMyRank(userRankModel.getMyRank(playerId));
        }

        builder.setRank(listBuilder);
        return builder;
    }

    public NewMonopolyMarketProto.NewMonopolyMarketServerRankListRespMsg.Builder getServerRankList(long serverId, long playerId) {
        NewMonopolyMarketProto.NewMonopolyMarketServerRankListRespMsg.Builder builder = NewMonopolyMarketProto.NewMonopolyMarketServerRankListRespMsg.newBuilder();

        for (ServerRank serverRank : serverRankModel.getRankList()) {
            NewMonopolyMarketProto.NewMonopolyMarketServerRankTemp.Builder rank = NewMonopolyMarketProto.NewMonopolyMarketServerRankTemp.newBuilder();
            rank.setServerId(serverRank.getServerId());
            rank.setValue(serverRank.getValue().toString());
            builder.addRank(rank);
        }
        return builder;
    }

    private int getHourTime() {
        //当前小时时间 + 30分钟
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);
        return (int)(calendar.getTimeInMillis() / 1000);
    }

    public void statResUseInfo() {

        int currentTime = getHourTime();
        if(currentTime > weekStateData.getLastStatTime()){

            List<LogNewMonopolyMarketResUseStat> list = new ArrayList<>();
            //榷署
            if(NewMonopolyMarketCommonMgr.isSystemOpenTime(eMonopolyMarketResType.OFFICE_NEW.getValue())){
                if(getMarketOffice().getSeatConfigList() != null){
                    for (MonopolyMarketOfficeSeatConfig seatConfig : getMarketOffice().getSeatConfigList()) {
                        int empty = 0;
                        int total = seatConfig.getEndIndex() - seatConfig.getStartIndex() + 1;
                        for (int i = seatConfig.getStartIndex(); i <= seatConfig.getEndIndex(); i++) {
                            NewMonopolyMarketOfficeSeatInfo seatInfo = getMarketOffice().getSeatDataMap().get(i);
                            if(seatInfo != null && seatInfo.baseInfo.getPlayerId() == 0){
                                empty++;
                            }
                        }
                        LogNewMonopolyMarketResUseStat log = new LogNewMonopolyMarketResUseStat(
                                weekStateData.getWeekId(),
                                weekStateData.getSystemGroupId(),
                                0,
                                eMonopolyMarketResType.OFFICE_NEW.getValue(),
                                seatConfig.level,
                                total,
                                empty);
                        list.add(log);
                        CrossAutoLogMgr.add(log);
                    }
                    CrossNewMonopolyMarketMgr.getLogger().info("统计榷署位置end");
                }
            }

            if(NewMonopolyMarketCommonMgr.isSystemOpenTime(eMonopolyMarketResType.RES_KING_NEW.getValue())){
                //按资源分组
                for (Map.Entry<Integer, NewMonopolyMarketResGrab> resGrabEntry : getMarketResRob().getMarketResGrabMap().entrySet()) {
                    Map<Integer, Integer> lvTotalMap = new HashMap<>();
                    NewMonopolyMarketResGrab resGrab = resGrabEntry.getValue();
                    if(resGrab.map == null){
                        continue;
                    }
                    Map<Integer, Integer> lvEmptyMap = new HashMap<>();
                    for (Map.Entry<Integer, Integer> entry : resGrab.map.indexLevelMap.entrySet()) {
                        int index = entry.getKey();
                        int lv = entry.getValue();
                        if (lv == 0) {
                            continue;
                        }
                        NewMonopolyMarketResGrabPointInfo pointInfo = marketResRob.getMonopolyMarketResGrabPointInfo(resGrab, index, false);
                        if(pointInfo == null){
                            continue;
                        }
                        int total = lvTotalMap.getOrDefault(lv, 0);
                        lvTotalMap.put(lv, total + 1);
                        if(pointInfo.baseInfo.getUserId() == 0) {
                            int empty = lvEmptyMap.getOrDefault(lv, 0);
                            lvEmptyMap.put(lv, empty + 1);
                        }
                    }
                    for (Map.Entry<Integer, Integer> entry : lvTotalMap.entrySet()) {
                        int lv = entry.getKey();
                        int total = entry.getValue();
                        LogNewMonopolyMarketResUseStat log = new LogNewMonopolyMarketResUseStat(
                                weekStateData.getWeekId(),
                                weekStateData.getSystemGroupId(),
                                resGrab.getResGroupId(),
                                resGrab.type,
                                lv,
                                total,
                                lvEmptyMap.getOrDefault(lv, 0));
                        list.add(log);
                        CrossAutoLogMgr.add(log);
                    }
                }
            }
            if(list.size() > 0) {
                CrossNewMonopolyMarketMgr.getLogger().info("统计王帐、王宫资源点位置end");
//                NewMonopolyMarketLogMgr.addLogNewMonopolyMarketResUseStat(list);
                weekStateData.setLastStatTime(currentTime);
            }
        }
    }
}
